package com.jic.market.impl.rest.promotion.promotionInfoHandler;

import com.google.common.collect.Maps;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * description: BaseInfoHandlerFactory
 * date: 2020/4/8 16:42
 * author: wangys
 * version: 1.0
 */
@Component
public class BaseInfoHandlerFactory implements InitializingBean, ApplicationContextAware {
    @Setter
    private ApplicationContext applicationContext;

    private Map<String, BaseInfoHandler> handlerHashMap = Maps.newHashMap();

    private Map<List<Integer>, BaseInfoHandler> frontTypeHandlerHashMap = Maps.newHashMap();

    @Override
    public void afterPropertiesSet() throws Exception {
        applicationContext.getBeansOfType(BaseInfoHandler.class)
                .forEach((k, v) -> {
                   if(v.enable()){
                       handlerHashMap.put(v.handlerCode(), v);
                       frontTypeHandlerHashMap.put(v.frontPromTypes(), v);
                   }
                });
    }

    public BaseInfoHandler getBaseInfoHandler(String handlerCode) {
        return handlerHashMap.get(handlerCode);
    }

    public BaseInfoHandler getPromotionHandlerByFrontType(Integer frontType) {
        BaseInfoHandler handler = null;
        if(frontType == null){
            return handler;
        }
        for (Map.Entry<List<Integer>, BaseInfoHandler> listBaseInfoHandlerEntry : frontTypeHandlerHashMap.entrySet()) {
            if(listBaseInfoHandlerEntry.getKey().contains(frontType)){
                handler = listBaseInfoHandlerEntry.getValue();
                break;
            }
        }
        return handler;
    }

    public List<BaseInfoHandler> getBaseInfoHandlers() {
        List<BaseInfoHandler> baseInfoHandlers = new ArrayList<>();
        handlerHashMap.forEach((k, v)->{
            baseInfoHandlers.add(v);
        });
        return baseInfoHandlers;
    }
}
